﻿using System;
using System.Web;
using System.Web.Compilation;

using BizElements.BusinessLayer;

namespace BizElements.Web
{
    /// <summary>
    /// Creates resource providers which retrieve local and global resources through underlying <see cref="DbTextSource"/> objects.
    /// </summary>
    /// <remarks>
    /// ASP.NET must be configured to use this factory.
    /// <example>
    /// The following example shows how to use <b>DbResourceProviderFactory</b> from the <b>MySolution.WebApplication</b> assembly (web application).
    /// <code>
    /// &lt;system.web&gt;
    ///     &lt;globalization resourceProviderFactoryType="BizElements.BusinessLayer.DbResourceProviderFactory, BizElements.BusinessLayer" /&gt;
    /// &lt;system.web&gt;
    /// </code>
    /// </example>
    /// </remarks>
    public class DbResourceProviderFactory : ResourceProviderFactory
    {
        /// <summary>
        /// Initializes a new instance of <b>DbResourceProviderFactory</b> class.
        /// </summary>
        public DbResourceProviderFactory()
        {
        }

        /// <summary>
        /// Creates a global resource provider.
        /// </summary>
        /// <param name="classKey">Application module. Full class name (assembly type and resource type).</param>
        /// <returns>An DbResourceProvider object for the specified module.</returns>
        public override IResourceProvider CreateGlobalResourceProvider(string classKey)
        {
            string module = classKey;
            return new DbResourceProvider(new DbTextSource(module));
        }

        /// <summary>
        /// Creates a local resource provider.
        /// </summary>
        /// <param name="virtualPath">The path to an application module. Application path is removed from virutalPath to create a module name.</param>
        /// <returns>An DbResourceProvider object for the module specified by virtualPath.</returns>
        public override IResourceProvider CreateLocalResourceProvider(string virtualPath)
        {
            // virtualPath = applicationPath + "/" + modulePath
            string module = TextUtil.RemovePrefix(virtualPath, HttpContext.Current.Request.ApplicationPath, StringComparison.InvariantCultureIgnoreCase);
            module = TextUtil.RemovePrefix(module, "/");
            return new DbResourceProvider(new DbTextSource(module));
        }
    }
}
